package com.bw.jetpacktest.live;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import com.bw.jetpacktest.R;

/**
 * 同一线程间传递数据,
 * 不同线程间传递数据,
 * 防止livedata数据倒灌
 * livedata数据倒灌:livedata进行多个观察者绑定时,A操作了Livedata得数据
 * B观察者绑定时，直接收到A操作得数据，数据倒灌
 * observeForever->livedata绑定
 * observe->livedata绑定，livedata绑定activity生命周期->当activitydestroy
 * 销毁时，livedata移除activity绑定过来得观察者
 * 1.创建MutableLiveData对象
 * */
public class LiveActivity extends AppCompatActivity implements View.OnClickListener {

    private SetTest setTest;
    private PostTest postTest;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liverdata);
        findViewById(R.id.set_btn).setOnClickListener(this);
        findViewById(R.id.post_btn).setOnClickListener(this);
        findViewById(R.id.receve_btn).setOnClickListener(this);
        initLiveData();
    }

    private void initLiveData(){
        setTest = new SetTest();
        postTest = new PostTest();
        setTest.getLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                //当livedata被观察者数据改变时,绑定得Observer->onChanged方法接受到改变得数据
                Log.e("ZXY","onChanged->"+s);
            }
        });
        postTest.getLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                //
                Toast.makeText(LiveActivity.this,s,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.set_btn:
                setTest.setValue("hehe");
                break;
            case R.id.post_btn:
                postTest.setValue("post");
                break;
            case R.id.receve_btn:

                break;
        }
    }
}
